import Vue from 'vue'
import Vuex from 'vuex'
import { asyncRoutes, menu, resetRouter } from '@/router'

Vue.use(Vuex)

// 通过递归过滤asyncRoutes
export function filterAsyncRoutes (routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  console.log('res', res)
  return res
}

function hasPermission (roles, route) {
  if (route.meta && route.meta.role) {
    // some() 方法用于检测数组中的元素是否满足指定条件（函数提供）
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
  } else {
    return true
  }
}

const store = new Vuex.Store({
  state: {
    userName: JSON.parse(localStorage.getItem('userName')) || {},
    token: JSON.parse(localStorage.getItem('userToken')) || {},
    routers: menu,
    addRouters: [],
    roles: [],
    uid: Number
  },
  getters: {
    getUserName: function (state) {
      return state.userName
    },
    getToken: function (state) {
      return state.token
    },
    getRoutes: function (state) {
      return state.routers
    },
    getAddRouters: function (state) {
      return state.addRouters
    },
    getRoles: state => state.roles,
    getUid: state => state.uid
  },
  mutations: {
    changeUserName (state, userName) {
      localStorage.setItem('userName', JSON.stringify(userName)) // 将传递的数据先保存到localStorage中
      state.userName = userName
    },
    saveToken (state, token) {
      localStorage.setItem('userToken', JSON.stringify(token)) // 将传递的数据先保存到localStorage中
      state.token = token
    },
    SET_ROUTES: (state, routers) => {
      state.addRouters = routers
      state.routers = menu.concat(routers)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_UID: (state, uid) => {
      state.uid = uid
    }
  },
  actions: {
    changeUserName (context, userName) {
      context.commit('changeUserName', userName)
    },
    saveToken (context, token) {
      context.commit('saveToken', token)
    },
    setRoles (context, roles) {
      context.commit('SET_ROLES', roles)
    },
    generateRoutes ({ commit }, roles) {
      return new Promise(resolve => {
        let accessedRoutes
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    },
    setUid (context, uid) {
      context.commit('SET_UID', uid)
    },
    // remove token
    resetToken ({ commit }) {
      return new Promise(resolve => {
        localStorage.removeItem('userToken')
        localStorage.removeItem('userName')
        commit('saveToken', '')
        commit('SET_ROLES', [])
        resetRouter()
        resolve()
      })
    }
  }
})

export default store
